"""Console script for napi_gen."""
import os
import typer
import argparse
from rich.console import Console
from . import utils
from . import napi_parser

app = typer.Typer()
console = Console()


@app.command()
def main(
    input_file: str = typer.Argument(..., help="Input .d.ts file"),
    module_name: str = typer.Option(..., "--module-name", "-m", help="Input module name"),
    output_file: str = typer.Option(None, "--output", "-o", help="Output napi cpp files"),
    verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output")
    ):
    """Console script for napi_gen.

    Example:

        napi-gen --input mylib.d.ts --module-name mylib --output bindings.cpp
    """
    os.makedirs("out", exist_ok=True)
    
    # input_path,nm_module = utils.extract_filename_without_extension(input_file)
    nm_module = module_name
    if output_file is None:
        out_napi_file = f"out/{nm_module}_napi.cpp"
        out_test_file = f"out/{nm_module}_test.ets"
    else:
        out_path, out_name = utils.extract_filename_without_extension(output_file)
        out_napi_file = f"{out_path}/{out_name}.cpp"
        out_test_file = f"{out_path}/{out_name}.ets"

    result = napi_parser.parse_dts(dts_file=input_file)
    # 导出为JSON文件
    utils.export_to_json(result, 'out/parsed_result.json')
    print(f"\n详细结果已导出到 'out/parsed_result.json'")

    napiBlocks = napi_parser.gen_napi_code(result, nm_module, module_name)
    
    with open(out_napi_file, 'w') as f:
        f.write('#include "ohos_utils/napi_handler.h"\n\n')
        for block in napiBlocks:
            f.write(str(block))

    testBlocks = napi_parser.gen_test_code(result, nm_module, module_name)
    with open(out_test_file, 'w') as f:
        for block in testBlocks:
            f.write(str(block) + '\n\n')

if __name__ == "__main__":
    app()
